package retrofit2.spring.factory;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import retrofit2.Retrofit;

/**
 * RetrofitClientFactoryBean
 * <p>
 * 工厂类负责实现 RetrofitClient
 *
 * @author archx
 * @since 2020/7/2 11:12
 */
public class RetrofitClientFactoryBean implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Class<?> resourceClass;

    @Override
    public Object getObject() throws Exception {
        return getRetrofit().create(resourceClass);
    }

    @Override
    public Class<?> getObjectType() {
        return resourceClass;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(resourceClass, "接口类型不能为空");
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void setResourceClass(Class<?> resourceClass) {
        this.resourceClass = resourceClass;
    }

    private Retrofit getRetrofit() {
        return applicationContext.getBean(Retrofit.class);
    }
}
